package com.wondertek.service.service.business.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wondertek.common.base.Result;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.log.AutoLogUtil;
import com.wondertek.common.util.base.StringUtil;
import com.wondertek.common.util.security.LoginUser;
import com.wondertek.common.util.security.SecurityUtil;
import com.wondertek.service.dto.app.req.InstallerPageDeviceReq;
import com.wondertek.service.dto.app.req.InstallerPageRoomReq;
import com.wondertek.service.dto.app.res.*;
import com.wondertek.service.dto.business.res.SiteDeviceAccessoryRes;
import com.wondertek.service.entity.business.AccessoryPo;
import com.wondertek.service.entity.business.DevicePo;
import com.wondertek.service.entity.business.RoomPo;
import com.wondertek.service.mapper.business.InstallerMapper;
import com.wondertek.service.sdk.iotdh.dto.Net;
import com.wondertek.service.sdk.iotdh.dto.Power;
import com.wondertek.service.sdk.iotdh.dto.req.GetAccessoryInfoReq;
import com.wondertek.service.sdk.iotdh.dto.req.GetAreaInfosReq;
import com.wondertek.service.sdk.iotdh.dto.req.GetStatusReq;
import com.wondertek.service.sdk.iotdh.dto.req.SetAccessoryPairReq;
import com.wondertek.service.sdk.iotdh.dto.res.*;
import com.wondertek.service.sdk.iotdh.service.DhDeviceService;
import com.wondertek.service.service.business.AccessoryService;
import com.wondertek.service.service.business.DeviceService;
import com.wondertek.service.service.business.InstallerService;
import com.wondertek.service.service.business.RoomService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyu
 */
@Service
public class InstallerServiceImpl implements InstallerService {

    private static final Logger log = LoggerFactory.getLogger(InstallerServiceImpl.class);

    @Autowired
    private InstallerMapper installerMapper;

    @Autowired
    private DhDeviceService dhDeviceService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private AccessoryService accessoryService;

    @Autowired
    private RoomService roomService;

    private static final List<DaKvRes> deviceTypes = new ArrayList<>();
    private static final List<DaKvRes> accessoryTypes = new ArrayList<>();
    {
        {
            deviceTypes.add(new DaKvRes("2004","Alarm Hub",null));
            deviceTypes.add(new DaKvRes("2007","IPC",null));
            accessoryTypes.add(new DaKvRes("1","Smoke detector","HY-SA21A"));
            accessoryTypes.add(new DaKvRes("2","Wireless keyfob","ARA24"));
            accessoryTypes.add(new DaKvRes("3","External Siren","ARA13"));
            accessoryTypes.add(new DaKvRes("4","Door Detector","ARD323"));
            accessoryTypes.add(new DaKvRes("5","Door Detector Plus","ARD324"));
            accessoryTypes.add(new DaKvRes("6","Pir Detertor","ARD1233"));

        }
    }

    @Override
    public List<KvRes> findAllSiteByUserId() {
        LoginUser loginUser = SecurityUtil.getLoginUser();
        return installerMapper.findAllSiteByUserId(loginUser.getUserId());
    }

    @Override
    public Page<AppDevicePageByUserIdRes> pageDeviceBySiteId(InstallerPageDeviceReq req) {


        Page<AppDevicePageByUserIdRes> appDevicePageByUserIdResPage = installerMapper.pageDeviceBySiteId(req, new Page<>(req.getPageNo(), req.getPageSize()));

        if (appDevicePageByUserIdResPage == null)
            return null;

        List<AppDevicePageByUserIdRes> list = appDevicePageByUserIdResPage.getRecords();

        if (CollectionUtils.isNotEmpty(list)) {
            //获取设备的实时状态-在线离线
//            List<String> ids = list.stream().filter(d ->99!=d.getType())
//                    .map(AppDevicePageByUserIdRes::getCode)
//                    .filter(e -> StringUtils.isNotBlank(e)).collect(Collectors.toList());
//            DeviceListReq deviceListReq = new DeviceListReq();
//            deviceListReq.setPageSize(list.size());
//            deviceListReq.setDeviceIds(ids);
//            Result<DevicePageRes> devicePageResResult = dhDeviceService.pageDevice(deviceListReq);
            //    if(devicePageResResult.getData()!=null){
            //      DevicePageRes devicePageRes = JSONObject.parseObject(String.valueOf(devicePageResResult.getData()),DevicePageRes.class);
            //    if(devicePageRes!=null && CollectionUtils.isNotEmpty(devicePageRes.getRecords())){
            //       Map<String,Integer> statusMap = devicePageRes.getRecords().stream()
            //              .collect(Collectors.toMap(DeviceRes::getDeviceId, DeviceRes::getStatus));
            for (AppDevicePageByUserIdRes res : list) {
                //         Integer status = statusMap.get(res.getCode());
                //        res.setStatus(status==null ? 0 : status);
                if (2 == res.getType()) {
                    if (1 == res.getStatus()) {
                        GetStatusReq getStatusReq = new GetStatusReq();
                        getStatusReq.setDeviceId(res.getSnCode());
                        try {
                            Result<GetStatusRes> statusRes = dhDeviceService.getStatus(getStatusReq);
                            GetStatusRes getStatusRes = statusRes.getData();
                            if (getStatusRes != null) {
                                Net net = getStatusRes.getNet();
                                Power power = getStatusRes.getPower();
                                if (net != null) {
                                    res.setWifiIntensity(net.getWirelessNetworkIntensity()!=null?String.valueOf(net.getWirelessNetworkIntensity()):null);
                                }
                                if (power != null) {
                                    res.setBatteryPercent(power.getBatteryPercent());
                                }
                            }
                        } catch (Exception e) {
                            log.info("error:" + e.getMessage());
                            res.setWifiIntensity("0");
                            res.setBatteryPercent(0);
                        }

                    } else {
                        res.setWifiIntensity("0");
                        res.setBatteryPercent(0);
                    }
                }
            }
            //      }
            //       }
//            for(AppDevicePageByUserIdRes pageRes : list){
//                GetAccessoryInfoReq getAccessoryInfoReq = new GetAccessoryInfoReq();
//                String deviceSn = pageRes.getDeviceSn();
//                getAccessoryInfoReq.setDeviceId(pageRes.getDeviceSn());
//                if(StringUtils.isNotBlank(deviceSn)){
//                    List<String> accessoryIds = new ArrayList<>();
//                    accessoryIds.add(pageRes.getCode());
//                    getAccessoryInfoReq.setAccessoryIds(accessoryIds);
//                    Result<List<GetAccessoryInfoRes>> accessoryInfo = dhDeviceService.getAccessoryInfo(getAccessoryInfoReq);
//                    List<GetAccessoryInfoRes> data = accessoryInfo.getData();
//                    if(CollectionUtils.isNotEmpty(data)){
//                        Integer status = data.get(0).getOnline();
//                        if(status==2){
//                            pageRes.setStatus(1);
//                        }
//                    }
//                }
//            }
        }
        //根据在线条件筛选数据
//        if(req.getStatus()!=null){
//            list = list.stream().filter(e ->req.getStatus()==e.getStatus()).collect(Collectors.toList());
//        }
        appDevicePageByUserIdResPage.setRecords(list);
        return appDevicePageByUserIdResPage;
    }

    @Override
    public Page<InstallerRoomRes> pageRoomByDeviceId(InstallerPageRoomReq req) {
        Page<InstallerRoomRes> roomRes = installerMapper.pageRoomByDeviceId(req, new Page<>(req.getPageNo(), req.getPageSize()));
        List<InstallerRoomRes> records = roomRes.getRecords();
        for (InstallerRoomRes r : records) {
            GetAreaInfosReq getAreaInfosReq = new GetAreaInfosReq();
            getAreaInfosReq.setDeviceId(r.getSnCode());
            getAreaInfosReq.setAreaId(r.getRoomCode());
            Result<GetAreaArmModeRes> areaArmMode = null;
            try {
                areaArmMode = dhDeviceService.getAreaArmMode(getAreaInfosReq);

            } catch (Exception e) {
                return roomRes;
            }

            //      ArmModesRes armModesRes = JSONObject.parseObject(String.valueOf(areaArmMode.getData()), ArmModesRes.class);

            ArmModesRes armModesRes = null;
            try {
                List<ArmModesRes> armModes = JSONArray.parseArray(JSONObject.parseObject(String.valueOf(areaArmMode.getData())).get("armModes").toString(), ArmModesRes.class);
                if (armModes != null && !armModes.isEmpty())
                    armModesRes = armModes.get(0);
            } catch (Exception e) {
                throw new AppException("调用大华异常");
            }

            //   ArmModesRes armModes = arm
            r.setMode(armModesRes.getMode());
        }


        return roomRes;
    }

    @Override
    public InstallerScanRes scan(String scan) {

        log.info("scan:"+scan);

        if(StringUtil.isEmpty(scan))
            throw new AppException("scan is null");

        InstallerScanRes res = new InstallerScanRes();

        String findReq = "";
//     Dl:AlarmHub:设备 其他配件   // 失败为IPC
        if (scan.contains("Dl:AlarmHub")) {  //网关
            res.setDeviceType(1);
            res.setDeviceCode("2004");
            res.setDeviceNameEn("AlarmHub");
            res.setDeviceNameZh("网关");
        } else if (scan.contains("Dl:PIRDetector")) {  //PlR相机
            res.setDeviceType(2);
            res.setDeviceCode("6");
            res.setDeviceNameEn("PIRDetector");
            res.setDeviceNameZh("pir相机");
        } else if (scan.contains("Dl:DoorDetectorPlus")) {  // 门磁plus
            res.setDeviceType(2);
            res.setDeviceCode("5");
            res.setDeviceNameEn("DoorDetectorPlus");
            res.setDeviceNameZh("门磁plus");
        } else if (scan.contains("Dl:DoorDetector")) {  // 门磁
            res.setDeviceType(2);
            res.setDeviceCode("4");
            res.setDeviceNameEn("DoorDetector");
            res.setDeviceNameZh("门磁");
        } else if (scan.contains("Dl:Keyfob")) {  //无线遥控
            res.setDeviceType(2);
            res.setDeviceCode("2");
            res.setDeviceNameEn("Keyfob");
            res.setDeviceNameZh("无线遥控");
        } else if (scan.contains("Dl:Externaliren")) {  //室外警号
            res.setDeviceType(2);
            res.setDeviceCode("3");
            res.setDeviceNameEn("Externaliren");
            res.setDeviceNameZh("室外警号");
        } else if (scan.contains("DHI-ARC3000H-FW2")) {  //网关设备
            res.setDeviceType(1);
            res.setDeviceCode("2004");
            res.setDeviceNameEn("DHI-ARC3000H-FW2");
            res.setDeviceNameZh("网关");
        } else if (scan.contains("DHI-ARD1233-W2")) { //PIR相机
            res.setDeviceType(2);
            res.setDeviceCode("6");
            res.setDeviceNameEn("DHI-ARD1233-W2");
            res.setDeviceNameZh("PIR相机");
        } else if (scan.contains("DHI-HY-SA21A-W2")) { // 烟感
            res.setDeviceType(2);
            res.setDeviceCode("1");
            res.setDeviceNameEn("DHI-HY-SA21A-W2");
            res.setDeviceNameZh("烟感");
        } else if (scan.contains("DHI-ARD324-W2(S)")) {  //门磁plus
            res.setDeviceType(2);
            res.setDeviceCode("5");
            res.setDeviceNameEn("DHI-ARD324-W2(S)");
            res.setDeviceNameZh("门磁plus");
        } else if (scan.contains("DHI-ARD323-W2(S)")) { //门磁
            res.setDeviceType(2);
            res.setDeviceCode("4");
            res.setDeviceNameEn("DHI-ARD323-W2(S)");
            res.setDeviceNameZh("门磁");
        } else if (scan.contains("DHI-ARA24-W2")) {  //无线遥控
            res.setDeviceType(2);
            res.setDeviceCode("2");
            res.setDeviceNameEn("DHI-ARA24-W2");
            res.setDeviceNameZh("无线遥控");
        } else if (scan.contains("DHI-ARA13-W2(868)")) {  //室外警号
            res.setDeviceType(2);
            res.setDeviceCode("3");
            res.setDeviceNameEn("DHI-ARA13-W2(868)");
            res.setDeviceNameZh("室外警号");
        } else {  // IPC
            res.setDeviceType(1);
            res.setDeviceCode("2007");
            res.setDeviceNameEn("IPC");
            res.setDeviceNameZh("IPC");

            findReq = scan.substring(4);
        }

        if ("".equals(findReq))
            findReq = scan.substring(4, scan.indexOf(","));

        int num = 0;

        //查询配备或配件是否存在系统中
        if (res.getDeviceType() == 1) { // 设备
            String deviceNum = installerMapper.findDeviceNum(findReq);
            res.setSkCode(deviceNum);
            if (StringUtil.isNotEmpty(deviceNum))
                num = 1;
        } else
            num = installerMapper.findAccessoryNum(findReq);

        res.setExist(num > 0 ? 1 : 2);

    log.info("res:"+res);
        return res;
    }

    @Override
    public GetAccessoryInfoRes accessoryStatus(AccessoryStatusReq req) {
        GetAccessoryInfoReq dhReq = new GetAccessoryInfoReq();
        //   DevicePo device = deviceService.getById(room.getDeviceId());
        dhReq.setDeviceId(req.getDeviceSn());
        List<String> accessoryIds = new ArrayList<>();
        accessoryIds.add(req.getAccessorySn());
        dhReq.setAccessoryIds(accessoryIds);
        Result<List<GetAccessoryInfoRes>> accessoryInfo = dhDeviceService.getAccessoryInfo(dhReq);
        List<GetAccessoryInfoRes> list = accessoryInfo.getData();
        if (list == null || list.isEmpty())
            return null;

        return list.get(0);
    }

    @Override
    public List<DaKvRes> findDaTypes(Integer type) {
        return type ==1 ? deviceTypes : accessoryTypes;
    }


    /*
     * 挂载配件
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setAccessoryPair(SetAccessoryPairReq req) {
        //记录日志
        DevicePo devicePo = new DevicePo();
        devicePo.setSnCode(req.getDeviceId());
        SiteDeviceAccessoryRes res = deviceService.selectSiteDevice(devicePo);
        AutoLogUtil.save("sys","log.accessory.insert","配件sn码:"+req.getAccessoryInfo().getId(),
                res.getSiteName(),res.getDeviceSn(),res.getSiteId(),req.getAccessoryInfo().getId());
        //先查询该分区下是否已添加此配件
        LambdaQueryWrapper<AccessoryPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccessoryPo::getRoomId,req.getRoomId());
        queryWrapper.eq(AccessoryPo::getIsDelete,0);
        queryWrapper.eq(AccessoryPo::getAccessoryCode,req.getAccessoryInfo().getId());
        List<AccessoryPo> list = accessoryService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            throw new AppException("accessory.exist");
        }
        RoomPo byId = roomService.getById(req.getRoomId());

        if(byId == null)
            throw new AppException("room not exist!");

        req.getAccessoryInfo().setAreaId(byId.getRoomCode());

        try {
            dhDeviceService.setAccessoryPair(req);
        }catch (RestClientException | AppException e){
            log.info(e.getMessage());
            if(!"The accessory already exists.".equals(e.getMessage()))
                throw new AppException(e.getMessage());

        }

    }

}
